export default {
    // 将对象 转 url 参数
    urlEncode(obj) {
        var ret = [];
        for (var i in obj) {
            ret.push(i + "=" + obj[i])
        }
        return ret.join('&');
    },
    // 获取数字整数部分
    moneyToInt(number_) {
        let _n = parseFloat(number_).toFixed(2).split(".");
        return _n[0]
    },
    // 获取数字小数部分 number_ 数字 ，toFixed_ 小数位数
    moneyToOdd(number_, toFixed_) {
        if (toFixed_ <= 0) {
            return ""
        } else {
            let _n = parseFloat(number_).toFixed(toFixed_).split(".");
            return '.' + _n[1]
        }

    },


    // 返回数据类型
    toTypeof(v) {
        let _d = Object.prototype.toString.call(v)
        let _v = _d.substring(1, _d.length - 1).split(" ")[1]
        console.error(111, _v)
        return _v
    },

    // 数字转大写

    numberToChinese(str) {
        var num = parseFloat(str);
        var strOutput = "",
            strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
        num += "00";
        var intPos = num.indexOf('.');
        if (intPos >= 0) {
            num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
        }
        strUnit = strUnit.substr(strUnit.length - num.length);
        for (var i = 0; i < num.length; i++) {
            strOutput += '零壹贰叁肆伍陆柒捌玖'.substr(num.substr(i, 1), 1) + strUnit.substr(i, 1);
        }
        return strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零').replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1').replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿').replace(/^元/, "零元")

    },


    // 秒转 时分秒
    formatSeconds(value) {
        let result = parseInt(value)
        let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
        let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
        let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));

        let res = '';
        if (h !== '00') res += `${h}:`;
        res += `${m}:`;
        res += `${s}`;
        return res;
    },




    // 移动端系统判断
    isSystem() {
        if (navigator.userAgent.indexOf("CordovaAndroid") > -1) {
            // localStorage.setItem('systemType','android');
            return 'android';
        } else if (navigator.userAgent.indexOf("CordovaIOS") > -1) {
            // localStorage.setItem('systemType','ios');
            return 'ios';
        } else {
            localStorage.setItem('systemType', 'other');
            return 'other';
        }
    },
    //检查微信内核浏览器
    isWeixin() {
        let ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    },

    // 打印日志
    consoleLog(content_) {
        console.log('')
        console.log(content_)
    },
    // 获取地址栏参数
    getUrlQuery(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
    //  邮政编码校验
    isZipCode(_val) {
        return /^[1-9]{1}[0-9]{5}$/.test(_val);
    },
    //  限输入为数字或字母
    isNumberAndLetter(_val) {
        return /^[A-Za-z0-9]+$/.test(_val);
    },
    //  手机号校验
    isPhone(_val) {
        return /^1[123456789]\d{9}$/.test(_val);
    },
    isNumber(_val) {
        return /^[0-9]*$/.test(_val);
    },
    //判断整数和两位小数
    isNumber_xx(_val) {
        return /^\d+(\.\d{1,2})?$/.test(_val);
    },
    //判断密码由8-20位大小写字母和数字的
    isPassword(_val) {
        return /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}$/.test(_val);
    },
    //  千元分隔符
    isQianfen(_val) {
        return _val.toString().replace(/\B(?=(\d{3})+$)/g, ',');
    },

    //添加千位分隔符，并保留2位小数
    isMoneyQianfen(s) {

        if (/[^0-9\.]/.test(s)) return "invalid value";
        s = s.toString().replace(/^(\d*)$/, "$1.");
        s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
        s = s.replace(".", ",");
        var re = /(\d)(\d{3},)/;
        while (re.test(s)) {
            s = s.replace(re, "$1,$2");
        }
        s = s.replace(/,(\d\d)$/, ".$1");
        return s.replace(/^\./, "0.")
    },

    //uuuid
    getUuid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
    //   时间戳转格式
    timestampToDate(fmt, time_) {
        let myDate = new Date(time_);
        return this.getDateTime(fmt, myDate)
    },
    /**
     * 获取时间格式
     * 2020-02-02 02:02:02
     * this.$publicFn.getDateTime("yyyy-MM-dd HH:mm:ss")
     * 一天前
     * this.$publicFn.getDateTime("yyyy-MM-dd",new Date(new Date().getTime() - 1 * 24 * 60 * 60 * 1000)
     */
    getDateTime(fmt, myDate) {
        if (!myDate) {
            myDate = new Date();
        }

        let o = {
            "M+": myDate.getMonth() + 1, //月份
            "d+": myDate.getDate(), //日
            "H+": myDate.getHours(), //小时
            "m+": myDate.getMinutes(), //分
            "s+": myDate.getSeconds(), //秒
            "q+": Math.floor((myDate.getMonth() + 3) / 3), //季度
            "S": myDate.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (myDate.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (let k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    },



    // 加法
    countNumber_add(arg1, arg2) {
        // console.log(arg1, arg2);
        var r1, r2, m, c;
        try {
            r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        c = Math.abs(r1 - r2);
        m = Math.pow(10, Math.max(r1, r2));
        if (c > 0) {
            var cm = Math.pow(10, c);
            if (r1 > r2) {
                arg1 = Number(arg1.toString().replace(".", ""));
                arg2 = Number(arg2.toString().replace(".", "")) * cm;
            } else {
                arg1 = Number(arg1.toString().replace(".", "")) * cm;
                arg2 = Number(arg2.toString().replace(".", ""));
            }
        } else {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", ""));
        }
        return (arg1 + arg2) / m;
    },
    // 减法
    countNumber_sub(arg1, arg2) {
        let r1, r2, m, n
        try {
            r1 = arg1.toString().split('.')[1].length
        } catch (e) {
            r1 = 0
        }
        try {
            r2 = arg2.toString().split('.')[1].length
        } catch (e) {
            r2 = 0
        }
        m = Math.pow(10, Math.max(r1, r2))
        n = (r1 >= r2) ? r1 : r2
        return ((arg1 * m - arg2 * m) / m).toFixed(n)
    },
    // 乘法
    countNumber_mul(arg1, arg2) {
        let m = 0
        if (arg1 == null) {
            arg1 = 0
        }
        if (arg2 == null) {
            arg2 = 0
        }
        let s1 = arg1.toString()
        let s2 = arg2.toString()
        try {
            m += s1.split('.')[1].length
        } catch (e) { }
        try {
            m += s2.split('.')[1].length
        } catch (e) { }
        return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
    },
    // 除法
    countNumber_div(arg1, arg2) {
        let t1 = 0
        let t2 = 0
        let r1
        let r2
        try {
            t1 = arg1.toString().split('.')[1].length
        } catch (e) { }
        try {
            t2 = arg2.toString().split('.')[1].length
        } catch (e) { }
        r1 = Number(arg1.toString().replace('.', ''))
        r2 = Number(arg2.toString().replace('.', ''))
        let intDiv = r1 / r2
        let pow = Math.pow(10, t2 - t1)
        return this.countNumber_mul(intDiv, pow) // 这里用上面定义好的乘法运算
    },

    // 获取字符串长度（汉字算两个字符，字母数字算一个）
    getByteLen(val) {
        var len = 0;
        for (var i = 0; i < val.length; i++) {
            var a = val.charAt(i);
            if (a.match(/[^\x00-\xff]/ig) != null) {
                len += 2;
            } else {
                len += 1;
            }
        }
        return len;
    },
    // 获取对象第一个key值
    getObjectFirstKey(obj) {
        if (this.isEmpty(obj)) {
            return undefined;
        }
        let key;
        for (key in obj) {
            return key;
        }
        return key;
    },

    // 字符串 转 时间戳（秒）
    // 2015-03-05 17:59:00
    stringToTimestamp(date) {
        if (this.isEmpty(date)) {
			return "";
		}
        let _d = date.substring(0, 19);
        _d = _d.replace(/-/g, '/'); //必须把日期'-'转为'/'
        let _t = new Date(_d).getTime() / 1000;
        // 解析到异常结果
        if (this.isEmpty(_t)) {
            _t = date;
        }
        return _t;
    },


    // 时间戳(秒)转刚刚、N分钟前、今天几点几分、昨天几点几分等
    timestampFormat(timestamp) {
        if (this.isEmpty(timestamp)) {
			return "";
		}
        function zeroize(num) {
            return (String(num).length == 1 ? '0' : '') + num;
        }

        var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
        var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

        var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
        var tmDate = new Date(timestamp * 1000);  // 参数时间戳转换成的日期对象

        var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
        var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();

        if (timestampDiff < 60) { // 一分钟以内
            return "刚刚";
        } else if (timestampDiff < 3600) { // 一小时前之内
            return Math.floor(timestampDiff / 60) + "分钟前";
        } else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
            return '今天' + zeroize(H) + ':' + zeroize(i);
        } else {
            var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
            if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
                return '昨天' + zeroize(H) + ':' + zeroize(i);
            } else if (curDate.getFullYear() == Y) {
                return zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
            } else {
                return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
            }
        }
    },

    /**
     * 判断是否为空
     * 
     * isEmpty("") //true
     * isEmpty([]) //true
     * isEmpty({}) //true
     * isEmpty(0) //false
     * isEmpty(undefined) //true
     * isEmpty(null) //true
     * isEmpty(1) //false
     *
     * @param {*} val
     * @return {*} 
     */
    isEmpty(val) {
        // null or undefined
        if (val == null) return true;

        if (typeof val === 'boolean') return false;

        if (typeof val === 'number') return val == 0 ? false : !val;

        if (val instanceof Error) return val.message === '';

        switch (Object.prototype.toString.call(val)) {
            // String or Array
            case '[object String]':
            case '[object Array]':
                return !val.length;

            // Map or Set or File
            case '[object File]':
            case '[object Map]':
            case '[object Set]': {
                return !val.size;
            }
            // Plain Object
            case '[object Object]': {
                return !Object.keys(val).length;
            }
        }

        return false;
    },

    // 可选链操作符( ?. )
    // let a={ b:{ list:[ { b1:{ b11:"2" } }, { b2:{ b22:"2" } } ] } }
    // 使用 this.$vFN.Utils.optionalChain(a,"b.list.0.b1.b11") 
    optionalChain(val_, keys_) {
        if (this.isEmpty(keys_) || this.isEmpty(val_)) {
            return undefined;
        }
        let _arr = keys_.split(".");
        if (_arr.length <= 0) {
            return undefined;
        }
        if (this.isEmpty(val_[_arr[0]])) {
            return undefined;
        }
        if (_arr.length == 1) {
            return val_[_arr[0]]
        }
        return this.optionalChain(val_[_arr[0]], _arr.splice(1, _arr.length).join("."))
    },

    // 对象 深度  合并 [对象1，对象2,等] 。返回 深度合并后的{...对象1,...对象2,等}
    deepMerge(list_) {
        let _newObj = {};
        list_.forEach(item => {
            _newObj = this.deepMergeItem(_newObj, item)
        })
        return _newObj
    },
    deepMergeItem(obj1, obj2) {
        let key;
        for (key in obj2) {
            // 如果target(也就是obj1[key])存在，且是对象的话再去调用deepMerge，否则就是obj1[key]里面没这个对象，需要与obj2[key]合并
            // 如果obj2[key]没有值或者值不是对象，此时直接替换obj1[key]
            obj1[key] =
                obj1[key] &&
                    obj1[key].toString() === "[object Object]" &&
                    (obj2[key] && obj2[key].toString() === "[object Object]") ?
                    this.deepMergeItem(obj1[key], obj2[key]) :
                    (obj1[key] = obj2[key]);
        }
        return obj1;
    },


}